package netWork;

import java.io.IOException;
import java.net.*;
import java.util.Scanner;

public class Client {
    //首先要创建socket对象，但是此处不需要手动指定端口号
    DatagramSocket socket = null;

    private String serverIp;
    private int serverPort;

    //构造方法：要传输服务器IP(目的IP)和服务器端口(目的端口)
    public Client(String serverIp, int serverPort) throws SocketException {
        this.serverIp = serverIp;
        this.serverPort = serverPort;
        //下面就是自动分配一个端口号
        socket = new DatagramSocket();
    }

    public void start() throws IOException {
        System.out.println("客户端启动");
        Scanner scanner = new Scanner(System.in);
        while(true){
            System.out.println("-> ");
            //1. 从控制台中读取请求数据
            String request = scanner.next();

            //2. 构造请求并发送
            DatagramPacket requestPacket = new DatagramPacket(request.getBytes(),
                    request.getBytes().length, InetAddress.getByName(serverIp),serverPort);

            socket.send(requestPacket);

            //3. 读取服务器的响应
            DatagramPacket responsePacket = new DatagramPacket(new byte[4096],4096);

            socket.receive(responsePacket);

            //4. 把响应转化成字符串，并显示到控制台上
            String response = new String(responsePacket.getData(),0,responsePacket.getLength());
            System.out.println(response);

        }
    }

    public static void main(String[] args) throws IOException {
        Client client = new Client("127.0.0.1",9090);
        client.start();
    }

}
